﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using Spaanjaars.ContactManager.Infrastructure.Domain;
using Spaanjaars.ContactManager.Infrastructure.UnitOfWork;
using Spaanjaars.ContactManager.Model;

namespace Spaanjaars.ContactManager.Repository.EF
{
    public class ContactPersonRepository : IContactPersonRepository, IUnitOfWorkRepository
    {
        private readonly IUnitOfWork _uow;

        public ContactPersonRepository(IUnitOfWork uow)
        {
            _uow = uow;
        }

        public Model.ContactPerson FindBy(int id)
        {
            return DataContextFactory.GetDataContext().ContactPeople.FirstOrDefault<ContactPerson>(cp => cp.Id == id);
        }

        public int Count()
        {
            return DataContextFactory.GetDataContext().ContactPeople.Count();
        }

        public IEnumerable<ContactPerson> FindAll()
        {
            return DataContextFactory.GetDataContext().ContactPeople.ToList();
        }

        public IEnumerable<ContactPerson> FindAll(int index, int count)
        {
            return DataContextFactory.GetDataContext().ContactPeople.Skip(index).Take(count).ToList();
        }

        public IEnumerable<Model.ContactPerson> QueryWith(ISpecification<Model.ContactPerson> specification)
        {
            return DataContextFactory.GetDataContext().ContactPeople.Where(specification.Predicate).AsQueryable();
        }

        public IEnumerable<ContactPerson> QueryWith(ISpecification<ContactPerson> specification, int index, int count)
        {
            return DataContextFactory.GetDataContext().ContactPeople.Where(specification.Predicate).Skip(index).Take(count).AsQueryable();
        }

        public void Save(Model.ContactPerson entity)
        {
            _uow.RegisterAmended(entity, this);
        }

        public void Add(Model.ContactPerson entity)
        {
            _uow.RegisterNew(entity, this);
        }

        public void Remove(Model.ContactPerson entity)
        {
            _uow.RegisterRemoved(entity, this);
        }

        public void PersistCreationOf(IAggregateRoot entity)
        {
            DataContextFactory.GetDataContext().AddObject("Contacts", entity);
        }

        public void PersistUpdateOf(IAggregateRoot entity)
        {
            // No implementation required as entities are self tracking
        }

        public void PersistDeletionOf(IAggregateRoot entity)
        {
            DataContextFactory.GetDataContext().DeleteObject(entity);
        }
    }
}
